package cn.com.twoke.app.pin_dou_dou.color;

import cn.com.twoke.app.pin_dou_dou.utils.ColorLabUtils;

import java.awt.Color;
import java.util.concurrent.ConcurrentHashMap;

public class CIE_2000_Cached implements ColorDifferenceCalculator {
    private static final ConcurrentHashMap<String, double[]> labCache = new ConcurrentHashMap<>();

    /**
     * 带缓存的 RGB 转 Lab 转换
     */
    public static double[] rgbToLabCached(Color color) {
        String key = color.getRGB() + "";
        return labCache.computeIfAbsent(key, k -> ColorLabUtils.rgbToLab(color));
    }

    /**
     * 批量计算色差
     */
    public static double[] deltaE(Color baseColor, Color[] colors) {
        double[] baseLab = rgbToLabCached(baseColor);
        double[] results = new double[colors.length];
        
        for (int i = 0; i < colors.length; i++) {
            double[] colorLab = rgbToLabCached(colors[i]);
            results[i] = CIE_2000.calculateCIEDE2000(
                baseLab[0], baseLab[1], baseLab[2],
                colorLab[0], colorLab[1], colorLab[2]
            );
        }
        
        return results;
    }

    @Override
    public double deltaE(Color color1, Color color2) {
        double[] lab1 = rgbToLabCached(color1);
        double[] lab2 = rgbToLabCached(color2);
        return CIE_2000.calculateCIEDE2000(
                lab1[0], lab1[1], lab1[2],
                lab2[0], lab2[1], lab2[2]
        );
    }
}